package cn.befory.service.impl;

import cn.befory.constants.CommonConstants;
import cn.befory.constants.UserConstants;
import cn.befory.dao.UserMapper;
import cn.befory.exception.ExceptionEnum;
import cn.befory.exception.SysException;
import cn.befory.pojo.User;
import cn.befory.service.LoginService;
import cn.befory.service.vo.LoginResult;
import cn.befory.tools.JwtToken;
import cn.befory.tools.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by befory on 2019/8/19.
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService{
    @Autowired
    UserMapper userMapper;

    @Autowired
    JwtToken jwtToken;

    @Override
    @Transactional
    public LoginResult login(String loginName, String password) throws Exception {
        List<User> users = userMapper.selectByLoginName(loginName);
        if(users == null || users.isEmpty() || users.size() > CommonConstants.ONE){
            throw new SysException(ExceptionEnum.LOGIN_NAME_ERROR);
        }
        User user = users.get(0);
        if (user.getPassword().equals(MD5Util.getMD5(password+user.getSalt()))){
            //匹配成功
            user.setOnline(UserConstants.Online.ONLINE.ordinal())
                    .setLoginCount((user.getLoginCount())+CommonConstants.ONE)
                    .setRecentLoginTime(System.currentTimeMillis());
            userMapper.update(user);
            String token = jwtToken.createToken(user);
            return new LoginResult().setLoginStatus(true).setToken(token).setUid(user.getId());
        }
        return new LoginResult().setLoginStatus(false).setToken("");
    }

//    public static void main(String[] args) {
//        System.out.println(System.currentTimeMillis());
//
//        System.out.println(MD5Util.getMD5("admin1567086003374"));
//    }
}
